package com.etbsms.service.impl;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import com.etbsms.dao.IRoleDAO;
import com.etbsms.dao.IUsersDAO;
import com.etbsms.domain.Role;
import com.etbsms.domain.Users;
import com.etbsms.form.QueryUsersForm;
import com.etbsms.form.UsersForm;
import com.etbsms.security.User;
import com.etbsms.service.IUsersService;
import com.etbsms.util.Constants;

@Service
@Component("usersService")
public class UsersServiceImpl implements IUsersService {
	
	@Autowired
	private IRoleDAO roleDAO;
	
	@Autowired
	private IUsersDAO usersDAO;

	@Override
	public void init() {
		Role role1 = roleDAO.get(Constants.ROLE_ROOT);	
		Role role2 = roleDAO.get(Constants.ROLE_KEYR);	
		Role role3 = roleDAO.get(Constants.ROLE_INTR);		
		
		Set<Role> roles = new HashSet<Role>();
		roles.add(role1);
		roles.add(role2);
		roles.add(role3);
		
		Users users = new Users();
		users.setEmail("kobea132@gmail.com");
		users.setUsername("root");
		users.setPassword("0000");
		users.setFullname("管理者");
		users.setRole(roles);
		usersDAO.save(users);
	}

	@Override
	public List<Users> getAll() {
		// TODO Auto-generated method stub
		return usersDAO.getAll();
	}

	@Override
	public boolean save(UsersForm form) {
		// TODO Auto-generated method stub
		
		Set<Role> role = new HashSet<Role>();
		for(String roleid : form.getRoles())
			role.add(roleDAO.get(roleid));		
		Users users = new Users(form);
		users.setRole(role);		
		return usersDAO.save(users);
	}

	@Override
	public boolean delete(int seq_no) {
		Users users = usersDAO.get(seq_no);
		users.setEnabled(false);
		return usersDAO.update(users);
	}

	@Override
	public boolean update(Users users) {
		// TODO Auto-generated method stub
		return usersDAO.update(users);
	}

	@Override
	public Users get(int seq_no) {
		// TODO Auto-generated method stub
		return usersDAO.get(seq_no);
	}

	@Override
	public QueryUsersForm query(QueryUsersForm form) {
		// TODO Auto-generated method stub
		return usersDAO.query(form);
	}

	@Override
	public boolean existUsername(String username) {
		// TODO Auto-generated method stub
		return usersDAO.existUsername(username);
	}
	
	@Override
	public boolean existEmail(String email) {
		// TODO Auto-generated method stub
		return usersDAO.existEmail(email);
	}

	@Override
	public User findUserByUsername(String username) {
		// TODO Auto-generated method stub
		return usersDAO.findUserByUsername(username);
	}

	@Override
	public Users get(String username, String password) {
		// TODO Auto-generated method stub
		return usersDAO.get(username, password);
	}
}
